package com.wangm.easyExcel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.converters.WriteConverterContext;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.NumberUtils;

import java.math.BigDecimal;

/**
 * 重写excel转integer转换器,控制小数转换失败
 *
 * @author wangmeng
 * @since 2024/8/9
 */
public class CustomsIntegerNumberConverter implements Converter<Integer> {

    private static volatile CustomsIntegerNumberConverter INSTANCE;

    private CustomsIntegerNumberConverter() {
    }


    public static CustomsIntegerNumberConverter getInstance() {
        if (INSTANCE == null) {
            synchronized (CustomsIntegerNumberConverter.class) {
                if (INSTANCE == null) {
                    INSTANCE = new CustomsIntegerNumberConverter();
                    return INSTANCE;
                }
            }
        }
        return INSTANCE;
    }


    @Override
    public Class<?> supportJavaTypeKey() {
        return Integer.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    /**
     * 重写数字转integer
     *
     * @param cellData            Excel cell data.NotNull.
     * @param contentProperty     Content property.Nullable.
     * @param globalConfiguration Global configuration.NotNull.
     * @return
     */
    @Override
    public Integer convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                     GlobalConfiguration globalConfiguration) {
        // 去除尾部0
        BigDecimal numberValue = cellData.getNumberValue().stripTrailingZeros();
        return Integer.valueOf(numberValue.toPlainString());
    }

    @Override
    public WriteCellData<?> convertToExcelData(WriteConverterContext<Integer> context) {
        return NumberUtils.formatToCellData(context.getValue(), context.getContentProperty());
    }

}
